package projectmanagerapp

class User {

	String firstName
	String lastName
	String userName
	String password
	String  role
	
	
	String toString() {
		"${lastName}, ${firstName}"	
	}
	
	
	
	static hasMany = [projectsManaged : Project, projects : Membership]	
		
	static mappedBy = [projectsManaged: 'projectManager']	
	
	def projects() { return memberships.collect{it.project}}
	
	List addToProjects(Project project) { 
		Membership.link(this, project) 
		return projects()
		 }
	
	List removeFromProjects(Project project) {
		 Membership.unlink(this, project)
		  return projects()
		   }
	static Membership link(user, project) { 
		def m = Membership.findByUserAndProject(user, project)
		 if (!m) { 
			 m = new Membership() 
			 user?.addToMemberships(m)
			  project?.addToMemberships(m) m.save() 
			  }
		  return m 
		  }
	
	static void unlink(user, project) {
		 def m = Membership.findByUserAndProject(user, project) 
		 if (m) { 
			 user?.removeFromMemberships(m)
			 project?.removeFromMemberships(m)
			  m.delete()
			    }
		  }
	
    static constraints = {
		
		firstName(blank: false, size: 1..20)
		lastName(blank: false, size: 1..20)
		userName(blank: false, unique: true, size: 6..16,matches: "[a-zA-Z0-9_]+")
		password(blank: false, size: 6..16,password: true,matches: "[a-zA-Z0-9_]+")		
		role(blank:false, inList:["Admin","Manager", "User"])
    }
}
